package server

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	__ "learn-srv/basic/proto"
	"learn-srv/handler/models"
	"learn-srv/untils"
	"time"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedLearnServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) UserLogin(_ context.Context, in *__.UserLoginReq) (*__.UserLoginResp, error) {
	var err error

	var user models.User
	if err = user.GetUserInfo(in.Username); err != nil {
		return nil, errors.New("用户查询失败")
	}

	if user.ID == 0 {
		user = models.User{
			Username: in.Username,
			Password: in.Password,
		}
		if err = user.CreateUser(); err != nil {
			return nil, errors.New("用户注册失败")
		}
	} else {
		if user.Password != in.Password {
			return nil, errors.New("账号密码错误")
		}
	}

	return &__.UserLoginResp{
		UserId: int64(user.ID),
	}, nil
}

// 发布课程
func (s *Server) AddCourse(_ context.Context, in *__.AddCourseReq) (*__.AddCourseResp, error) {
	var err error

	var user models.User
	if err = user.GetUserById(int(in.UserId)); err != nil {
		return nil, errors.New("用户查询失败")
	}

	if user.ID == 0 {
		return nil, errors.New("请前往登录")
	}

	if user.UType != 2 {
		return nil, errors.New("权限不足，不允许添加")
	}

	//解析时间
	startTime, err := time.Parse(time.DateTime, in.StratTime)
	if err != nil {
		return nil, errors.New("开始时间解析失败：" + err.Error())
	}
	endTime, err := time.Parse(time.DateTime, in.EntTime)
	if err != nil {
		return nil, errors.New("结束时间解析失败：" + err.Error())
	}

	var course models.Course
	course = models.Course{
		UserId:    int(in.UserId),
		Title:     in.Title,
		Price:     float64(in.Price),
		Desc:      in.Desc,
		Stock:     int(in.Stock),
		StartTime: &startTime,
		EndTime:   &endTime,
		Status:    1, //未开始
	}
	if err = course.CreateCourse(); err != nil {
		return nil, errors.New("课程添加失败")
	}

	//同步Redis库存
	untils.SyncCourseStock(int(course.ID), int(in.Stock))

	return &__.AddCourseResp{
		CourseId: int64(course.ID),
	}, nil
}

// 课程详情
func (s *Server) GetCourseDetail(_ context.Context, in *__.GetCourseDetailReq) (*__.GetCourseDetailResp, error) {
	var err error

	var course models.Course
	if err = course.GetCourseInfo(int(in.CourseId)); err != nil {
		return nil, errors.New("课程查询失败")
	}

	if course.ID == 0 {
		return nil, errors.New("该课程不存在")
	}

	return &__.GetCourseDetailResp{
		CourseId: int64(course.ID),
		UserId:   int64(course.UserId),
		Title:    course.Title,
		Price:    float32(course.Price),
		Desc:     course.Desc,
		Stock:    int64(course.Stock),
	}, nil
}

// 订单
func (s *Server) CreateOrder(_ context.Context, in *__.CreateOrderReq) (*__.CreateOrderResp, error) {
	var err error

	var user models.User
	if err = user.GetUserById(int(in.UserId)); err != nil {
		return nil, errors.New("用户查询失败")
	}

	var course models.Course
	if err = course.GetCourseInfo(int(in.CourseId)); err != nil {
		return nil, errors.New("课程查询失败")
	}

	if course.ID == 0 {
		return nil, errors.New("该课程不存在")
	}

	//判断库存
	stock := untils.GetCourseStock(int(in.CourseId))
	if stock < int(in.Number) {
		return nil, errors.New("库存不足")
	}

	//添加分布式锁
	if !untils.LockCourseStock(int(in.CourseId)) {
		return nil, errors.New("上锁失败")
	}

	//创建订单
	var order models.Order
	order = models.Order{
		UserId:     int(in.UserId),
		CourseId:   int(in.CourseId),
		OrderSn:    uuid.NewString(),
		OrderPrice: course.Price,
		Number:     int(in.Number),
		Status:     1, //待支付
	}
	if err = order.CreateOrder(); err != nil {
		return nil, errors.New("创建订单失败")
	}

	//扣减Redis库存
	if !untils.DeleteCourseStock(int(in.CourseId)) {
		return nil, err
	}

	//删除分布式锁
	t := time.Now().Unix()
	if order.CreatedAt.Unix() > t*15*3600 {
		untils.UnLockCourseStock(int(order.ID))
	}

	//生成支付链接
	url := untils.AliPay{}

	return &__.CreateOrderResp{
		OrderSn: order.OrderSn,
		PayUrl:  url.GetPayUrl(order.OrderSn, fmt.Sprintf("%.2f", order.OrderPrice)),
	}, nil
}

// 订单支付
func (s *Server) UpdateOrderStatus(_ context.Context, in *__.UpdateOrderStatusReq) (*__.UpdateOrderStatusResp, error) {
	var err error

	var order models.Order
	if err = order.GetOrderInfo(in.OrderSn); err != nil {
		return nil, errors.New("订单查询失败")
	}

	if order.ID == 0 {
		return nil, errors.New("该订单不存在")
	}

	order.Status = int(in.Status)
	if err = order.UpdateOrderStatus(in.OrderSn); err != nil {
		return nil, errors.New("修改订单失败")
	}

	if order.Status == 3 || order.Status == 4 {
		//扣减MySQL库存
		var course models.Course
		if err = course.GetCourseInfo(order.CourseId); err != nil {
			return nil, errors.New("课程查询失败")
		}

		if err = course.DelCourseStock(order.CourseId, order.Number); err != nil {
			return nil, errors.New("扣减库存失败")
		}
	}

	return &__.UpdateOrderStatusResp{}, nil
}

// 订单详情
func (s *Server) GteOrderDetail(_ context.Context, in *__.GteOrderDetailReq) (*__.GteOrderDetailResp, error) {
	var err error

	var order models.Order
	if err = order.GetOrderById(int(in.OrderId), int(in.UserId)); err != nil {
		return nil, errors.New("订单查询失败")
	}

	if order.ID == 0 {
		return nil, errors.New("该订单不存在")
	}

	var course models.Course
	if err = course.GetCourseInfo(order.CourseId); err != nil {
		return nil, errors.New("课程查询失败")
	}

	if course.ID == 0 {
		return nil, errors.New("该课程不存在")
	}

	return &__.GteOrderDetailResp{
		OrderSn:   order.OrderSn,
		CourseId:  int64(order.CourseId),
		Title:     course.Title,
		Price:     float32(order.OrderPrice),
		Desc:      course.Desc,
		Stock:     int64(order.Number),
		StratTime: "",
		EntTime:   "",
	}, nil
}
